<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="计划单号" prop="planId">
        <el-input v-model="queryParams.planId" placeholder="请输入计划单号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="项目名称" prop="projectName">
        <el-input v-model="queryParams.projectName" placeholder="请输入项目名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="施工单位" prop="buildUnitId">
        <el-input v-model="queryParams.buildUnitId" placeholder="请输入施工单位" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="联系人" prop="contactsId">
        <el-input v-model="queryParams.contactsId" placeholder="请输入联系人" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="运输地址" prop="transportAddr">
        <el-input v-model="queryParams.transportAddr" placeholder="请输入运输地址" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="计划月份" prop="planMonth">
        <el-date-picker clearable v-model="queryParams.planMonth" type="date" value-format="yyyy-MM-dd"
          placeholder="请选择计划月份">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['sale:delivery:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['sale:delivery:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-wallet" size="mini" :disabled="processTag" @click="handlerProcess"
          v-hasPermi="['sale:delivery:remove']">审核</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-delete" size="mini" :disabled="single" @click="planDecomposition"
          v-hasPermi="['sale:delivery:remove']">计划分解</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-wallet" size="mini" :disabled="processTagR" @click="handlerProcessR"
          v-hasPermi="['sale:delivery:remove']">反审核</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['sale:delivery:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['sale:delivery:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="deliveryList" @row-click="handleRowClick"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column fixed label="计划单号" align="center" prop="planId" v-if="columns[0].visible" width="170" />
      <el-table-column fixed label="项目名称" align="center" prop="projectName" v-if="columns[1].visible" width="200" />
      <el-table-column fixed label="标段" align="center" prop="lotSection" v-if="columns[2].visible" width="100">
        <template slot-scope="scope">
          <span>{{ scope.row.lotSectionCode }}</span>
        </template>
      </el-table-column>
      <el-table-column label="施工单位" align="center" prop="buildUnitId" v-if="columns[3].visible" width="200">
        <template slot-scope="scope">
          <span>{{ scope.row.buildUnitName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="联系人" align="center" prop="contacts" v-if="columns[4].visible" />
      <el-table-column label="联系人电话" align="center" prop="contactsTel" v-if="columns[5].visible" width="120" />
      <el-table-column label="运输地址" align="center" prop="transportAddr" v-if="columns[6].visible" width="200" />
      <el-table-column label="销售合同" align="center" prop="contractId" v-if="columns[7].visible" width="200">
        <template slot-scope="scope">
          <span>{{ scope.row.contractName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="计划月份" align="center" prop="planMonth" width="180" v-if="columns[8].visible">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.planMonth, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="收货人" align="center" prop="released" v-if="columns[9].visible" />
      <el-table-column label="到货点" align="center" prop="deliveryPoint" v-if="columns[10].visible" />
      <el-table-column label="审核状态" align="center" prop="reviewedStatus" fixed="right" v-if="columns[11].visible">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sms_audit_status" :value="scope.row.reviewedStatus" />
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="note" v-if="columns[12].visible" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="160" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['sale:delivery:edit']" v-if="scope.row.reviewedStatus != 1">编辑</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['sale:delivery:remove']">删除</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit-outline" @click="handlerProcess($event, scope.row)"
            v-hasPermi="['sale:delivery:process']" v-if="scope.row.reviewedStatus != 1">审核</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit-outline" @click="handlerProcessR($event, scope.row)"
            v-hasPermi="['sale:delivery:process']" v-if="scope.row.reviewedStatus == 1">反审核</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 计划分解 -->
    <div class="planDecompose" v-show="showPlanDecompose">
      <div class="line"></div>
      <h3 class="title">批次配送</h3>
      <div class="planDecomponse-table">
        <el-table :data="planDecomposeData" size="mini" border style="width: 100%" max-height="220">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column label="材料名称" prop="materialName" :show-overflow-tooltip="true" />
          <el-table-column label="钢号" prop="specifications" :show-overflow-tooltip="true" />
          <el-table-column label="规格型号" prop="steelNumber" :show-overflow-tooltip="true" />
          <el-table-column label="单价" prop="unitPrice" :show-overflow-tooltip="true" />
          <el-table-column label="计划数量" prop="planQuantity" :show-overflow-tooltip="true" />
          <el-table-column label="已做批次计划" prop="completedCount" :show-overflow-tooltip="true" />
          <el-table-column label="可分解数" align="center" prop="decomposableCount" />
          <el-table-column label="本次配送" prop="delivery">
            <template slot-scope="scope">
              <el-input type="text" size="mini" v-model="scope.row.delivery" />
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="dialog-footer">
        <el-button type="primary" @click="generateBatchPlan">确 定</el-button>
      </div>
    </div>


    <!-- 添加或修改月配送计划对话框 -->
    <el-dialog @close="handlerDataChange" :title="title" :visible.sync="open" width="900px" height="700" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row justify="space-between" type="flex">
          <el-col :span="12">
            <el-form-item label="项目名称" prop="projectName">
              <el-input v-model="form.projectName" placeholder="请输入项目名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="标段" prop="lotSection">
              <el-select v-model="form.lotSection" placeholder="请选择">
                <el-option v-for="item in lotOptions" :key="item.id" :label="item.code" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row justify="space-between">
          <el-col :span="12">
            <el-form-item label="施工单位" prop="buildUnitId">
              <el-select v-model="form.buildUnitId" placeholder="请选择">
                <el-option v-for="item in buildUnitOptions" :key="item.buildId" :label="item.buildName"
                  :value="item.buildId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="运输地址" prop="transportAddr">
              <el-input v-model="form.transportAddr" placeholder="请输入运输地址" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row justify="space-between">
          <el-col :span="12">
            <el-form-item label="联系人" prop="contacts">
              <el-input v-model="form.contacts" placeholder="请输入联系人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="contactsTel">
              <el-input v-model="form.contactsTel" placeholder="请输入联系人电话" maxlength="11" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="供应合同" prop="contract">
              <el-select v-model="form.contractId" placeholder="请选择">
                <el-option v-for="item in contractOptions" :key="item.contractId" :label="item.contractName"
                  :value="item.contractId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划月份" prop="planMonth">
              <el-date-picker clearable v-model="form.planMonth" type="date" value-format="yyyy-MM-dd"
                placeholder="请选择计划月份">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="收货人" prop="released">
              <el-input v-model="form.released" placeholder="请输入收货人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="到货点" prop="deliveryPoint">
              <el-input v-model="form.deliveryPoint" placeholder="请输入到货点" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="note">
              <el-input v-model="form.note" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-row>
        <el-col>
          <el-button @click="openAddMaterial(form.planId)" type="primary" style="margin-left: 16px;">
            材料选择
          </el-button>
          {{ form }}
          <div class="materialTab">
            <el-table :data="form.deliveryPlanDetails" size="mini" border style="width: 100%" max-height="220">
              <el-table-column type="selection" width="55"></el-table-column>
              <el-table-column label="材料名称" prop="materialName" :show-overflow-tooltip="true" />
              <el-table-column label="规格型号" prop="specifications" :show-overflow-tooltip="true" />
              <el-table-column label="钢号" prop="steelNumber" :show-overflow-tooltip="true" />
              <el-table-column label="类型" prop="meterialTypeId" :show-overflow-tooltip="true" />
              <el-table-column label="单价" align="center" prop="unitPrice" />
              <el-table-column label="计划数量" prop="planQuantity"></el-table-column>
              <el-table-column label="操作" width="80">
                <template slot-scope="scope">
                  <el-button type="text" icon="el-icon-delete" size="mini"
                    @click="handleDeleteMaterial(scope.$index, scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-drawer size="40%" title="添加材料" :visible.sync="drawer" :direction="direction" :before-close="handleClose">
      <add-material ref="add" @ok="changeSelectMaterial"></add-material>
    </el-drawer>
  </div>
</template>

<script>
import { listDelivery,addBatchWithDelivery, processDelivery, processReverseDelivery, getDelivery, delDelivery, addDelivery, updateDelivery } from "@/api/sale/delivery";
import { getBatchDetails} from "@/api/sale/batch";

import { listUnit } from "@/api/basic/unit.js"
import { listContractVo } from "@/api/basic/contract.js"
import { listLotVo } from "@/api/basic/lot.js"

import addMaterial from "./addMaterial";
import { compare } from '@/utils/materialDetail.js'
export default {
  name: "Delivery",
  dicts: ['sms_audit_status'],
  components: { addMaterial },
  data() {
    return {
      //计划分解表
      planDecomposeData: [],
      showPlanDecompose: false,
      isDataChanged: false,//弹框数据是否改变
      //施工单位、合同、标段的下拉框的options
      buildUnitOptions: [],
      contractOptions: [],
      materialData: [],
      lotOptions: [],
      //右侧抽屉是否显示
      drawer: false,
      direction: 'rtl',
      //反审核、审核按钮
      processTagR: true,
      processTag: true,
      //当前table选择的行
      checkRow: null,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 月配送计划表格数据
      deliveryList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        planId: null,
        projectName: null,
        buildUnitId: null,
        contactsId: '',
        contactsTel: null,
        transportAddr: null,
        planMonth: null,
        reviewedStatus: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        projectName: [
          { required: true, message: "项目名称不能为空", trigger: "blur" }
        ],
        lotSection: [
          { required: true, message: "桥段不能为空", trigger: "blur" }
        ],
        buildUnitId: [
          { required: true, message: "施工单位不能为空", trigger: "blur" }
        ],
        contactsId: [
          { required: true, message: "联系人不能为空", trigger: "blur" }
        ],
        contactsTel: [
          { required: true, message: "联系人电话不能为空", trigger: "blur" }
        ],
        transportAddr: [
          { required: true, message: "运输地址不能为空", trigger: "blur" }
        ],
        contractId: [
          { required: true, message: "供应合同不能为空", trigger: "blur" }
        ],
        planMonth: [
          { required: true, message: "计划月份不能为空", trigger: "blur" }
        ],
        releasedBy: [
          { required: true, message: "收货人不能为空", trigger: "blur" }
        ],
      },
      //隐显列
      columns: [
        { key: 0, label: `计划单号`, visible: true },
        { key: 1, label: `项目名称`, visible: true },
        { key: 2, label: `标段`, visible: true },
        { key: 3, label: `施工单位`, visible: true },
        { key: 4, label: `联系人`, visible: true },
        { key: 5, label: `联系人电话`, visible: true },
        { key: 6, label: `运输地址`, visible: true },
        { key: 7, label: `供应合同`, visible: true },
        { key: 8, label: `计划月份`, visible: true },
        { key: 9, label: `收货人`, visible: true },
        { key: 10, label: `到货点`, visible: true },
        { key: 11, label: `审核状态`, visible: true },
        { key: 12, label: `备注`, visible: true },
      ],
    };
  },
  created() {
    this.getList();
    this.init();
  },
  methods: {
    generateBatchPlan(){
      console.log(this.checkRow,'checkRow')
      let res = this.planDecomposeData.filter(item => item['delivery'] != 0)
      let row = this.checkRow
      console.log(res,'rese')
      const form = {"deliveryPlan":row,"deliveryPlanDetails":res}
      addBatchWithDelivery(form).then(response => {
        this.$modal.msgSuccess("批次计划生成成功");
        let planId = this.checkRow['planId']
        getBatchDetails(planId).then(response => {
          this.planDecomposeData = response.rows
        })
        //重新
      })
    },

    /**
     * 计划分解
     */
    planDecomposition() {
      console.log(this.checkRow, 'decompostion')

    },
    /**
     * 审核月配送计划
     * @param {*} row 
     */
    handlerProcess(click, row) {
      const r = row || this.checkRow
      this.$modal.confirm('是否通过"' + r['projectName'] + '"项目计划？').then(function () {
      }).then(() => {
        //发送请求，修改审核状态
        processDelivery(r.planId).then(response => {
          this.getList();
          this.$modal.msgSuccess("审核通过");
        })
      }).catch(() => { })
    },
    handlerDataChange() {
      console.log('退出dialog')
    },
    handlerProcessR(click, row) {
      const r = row || this.checkRow
      this.$modal.confirm('是否反审核项目"' + r.projectName + '"的数据项？').then(function () {
      }).then(() => {
        processReverseDelivery(r.planId).then(response => {
          this.getList()
          this.$modal.msgSuccess("反审核成功");
        })
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /**
     * 材料选择后的表格中的删除按钮
     */
    handleDeleteMaterial(index, row) {
      this.$modal.confirm('是否确认删除材料"' + row.materialName + '"的数据项？').then(function () {
      }).then(() => {
        const r = this.form['deliveryPlanDetails'].filter(item => {
          return item['materialName'] != row['materialName']
        })
        this.$modal.msgSuccess("删除成功");
        console.log(r, 'rrr', this.form['deliveryPlanDetails'])
        this.form['deliveryPlanDetails'] = []
        this.form['deliveryPlanDetails'] = r;
        console.log(this.form['deliveryPlanDetails'])
      }).catch(() => { });
    },
    /**
     * 改变选中的材料
     * @param {*} m 
     */
    changeSelectMaterial(m) {
      this.drawer = false;
      let materialData
      if (this.form['planId'] == null) {
        if (this.form['deliveryPlanDetails'] != null) {
          materialData = this.form['deliveryPlanDetails']
        } else {
          materialData = []
        }
      } else {
        materialData = this.form['deliveryPlanDetails']
      }
      materialData = compare(m, materialData)
      this.form['deliveryPlanDetails'] = materialData;
    },
    init() {
      listUnit(null).then(response => {
        this.buildUnitOptions = response.rows;
      }),
        listContractVo(null).then(response => {
          this.contractOptions = response.rows
        }),
        listLotVo(null).then(response => {
          this.lotOptions = response.rows
        })
    },
    openAddMaterial(planId) {
      this.drawer = true
      //发送请求获取数据
      setTimeout(() => {
        this.$refs.add.show(planId)
      }, 0)
    },
    /**抽屉显示，选择材料 */
    handleClose(done) {
      done();
      console.log(done, 'd')
    },
    /** 查询月配送计划列表 */
    getList() {
      this.loading = true;
      listDelivery(this.queryParams).then(response => {
        this.deliveryList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        planId: null,
        projectName: null,
        lotSection: null,
        buildUnitId: null,
        contacts: null,
        deliveryPlanDetails: null,
        contactsTel: null,
        transportAddr: null,
        contractId: null,
        planMonth: null,
        released: null,
        deliveryPoint: null,
        createBy: null,
        createTime: null,
        editedBy: null,
        editedTime: null,
        isDeleted: null,
        reviewedBy: null,
        reviewedStatus: null,
        reviewedTime: null,
        status: null,
        note: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleRowClick(row) {
      this.showPlanDecompose = false
      if (row['reviewedStatus'] != 0) {
        let planId = row['planId'];
        this.checkRow = row
        this.showPlanDecompose = true
        //发送请求获取数据
        getBatchDetails(planId).then(response => {
          this.planDecomposeData = response.rows
        })
        // this.planDecomposeData = row['deliveryPlanDetails']
      }
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.planId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
      console.log(selection, 'selection')
      if (selection.length == 1) {
        this.checkRow = selection[0];
        if (selection[0]['reviewedStatus'] == 1) {
          //反审核
          this.processTagR = false;
          this.processTag = true
          //"修改"按钮为disabled
          this.single = true;
        } else {
          //审核
          this.single = false;
          this.processTag = false
          this.processTagR = true;
        }
      } else {
        this.single = true;
        this.processTag = true
        this.processTagR = true;
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加月配送计划";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const planId = row.planId || this.ids
      getDelivery(planId).then(response => {
        console.log(response.data, 'res')
        this.form = response.data;
        //修改材料详情
        this.form['deliveryPlanDetails'] = row.deliveryPlanDetails
        this.open = true;
        this.title = "修改月配送计划";

      });
    },
    /** 提交按钮 */
    submitForm() {
      console.log(this.materialData, 'materialTab')
      this.$refs["form"].validate(valid => {
        if (valid) {
          let res = { "deliveryPlan": this.form, "deliveryPlanDetails": this.form.deliveryPlanDetails }
          if (this.form.planId != null) {
            updateDelivery(res).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            let res = { "deliveryPlan": this.form, "deliveryPlanDetails": this.form.deliveryPlanDetails }
            addDelivery(res).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const planIds = row.planId || this.ids;
      this.$modal.confirm('是否确认删除月配送计划编号为"' + planIds + '"的数据项？').then(function () {
        return delDelivery(planIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('sale/delivery/export', {
        ...this.queryParams
      }, `delivery_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style scoped>
.materialTab {
  margin: 20px;
}

.planDecompose {
  margin-top: 20px;
}
.planDecompose .planDecomponse-table{
  margin: 40px;
  margin-bottom: 0px;
}
.planDecompose .line {
  margin: 60px 0px 40px 0px;
  border-top: 3px #409eff solid;
}
.planDecompose .title{
  margin-left: 40px;
  margin-bottom: -20px;
}
.dialog-footer{
  margin-top: 20px;
  margin-right: 40px;
  text-align: right;
}
</style>